﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Portal.Language;
using Portal.Environment;
using System.Collections.ObjectModel;
using System.IO;

namespace Portal.CDSP
{
    public class RssChanelInfo
    {
        public string Url;
        public string SavedFile;
    }
    public class RssItemCls
    {
        public string ItemTitle;
        public string ItemDescription;
        public string Itemlink;
        public DateTime ItemPubDate;
        public string Image;

        public RssItemCls(
            string _ItemTitle,
            string _ItemDescription,
            string _ItemLink,
            DateTime _ItemPubDate,
            string _Image
            )
        {
            ItemTitle = _ItemTitle;
            ItemDescription = _ItemDescription;
            Itemlink = _ItemLink;
            ItemPubDate = _ItemPubDate;
            Image = _Image;
        }
    }
    public class RssChanelCls
    {
        public string ChanelId;
        public string ChanelTitle;
        public string ChanelUrl;
        public string ChanelSavePath;
        public string ChanelSaveFile;

        public RssChanelCls(
            string _ChanelId,
            string _ChanelTitle,
            string _ChanelUrl,
            string _ChanelSavePath,
            string _ChanelSaveFile)
        {
            ChanelId = _ChanelId;
            ChanelTitle = _ChanelTitle;
            ChanelUrl = _ChanelUrl;
            ChanelSavePath = _ChanelSavePath;
            ChanelSaveFile = _ChanelSaveFile;
        }
    }
    public class RSimpleSyndicationBLL
    {
        public DataTable ReadingForServiceForRss(string belongSite, string ActiveLanguage)
        {
            string Query =
            " SELECT [GroupNewsItemId] " +
                " ,[fk_GroupNews_Id] " +
                " ,[GroupNewsItemName]" +
                " ,[IndexOrder]" +
                " ,[ShortGroupNewsItemId]" +
                " ,[RssUrl]" +
                " ,[JumpUrl]" +
                " ,[vieGroupNewsItemName]    " +
                " ,[AllowRss]" +
                " FROM [TableGroupNewsItem]" +
                " where AllowRss = 1 and Visible = 1 " +
                " and IsGroupNews = 1 " +
                " and ShowInMenu =1 " +
                " and belongSite=@belongSite " +
                " order by IndexOrder ";


            //string Query = "select Id=GroupNewsItemId,Subject=[" + ActiveLanguage + "GroupNewsItemName] from TableGroupNews where belongSite='" + belongSite + "'";
            SqlConnection sqlConnection = new SqlConnection(Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = Query;
            sqlCommand.Parameters.Add("@belongSite", SqlDbType.VarChar);
            sqlCommand.Parameters["@belongSite"].Value = belongSite;
            DataTable dtResult = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
            da.Fill(dtResult);
            return dtResult;
        }
        public static RssChanelCls[] GetRssChannel(string Ext, string belongSite)
        {
            string Query = "select GroupNewsItemId,GroupNewsItemAlias,Subject=[" + belongSite + "GroupNewsItemName]  from TableGroupNewsItem where AllowRss=1" +
                " and IsGroupNews = 1 " +
                //" and ShowInMenu =1 " +
                " and belongSite=@belongSite " +
                " order by IndexOrder ";

            SqlConnection sqlConnection = new SqlConnection(Environment.Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = Query;
            sqlCommand.Parameters.Add("@belongSite", SqlDbType.VarChar);
            sqlCommand.Parameters["@belongSite"].Value = belongSite;
            DataTable dtResult = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
            da.Fill(dtResult);

            RssChanelCls[] rssChannels = new RssChanelCls[dtResult.Rows.Count];
            for (int iIndex = 0; iIndex < rssChannels.Length; iIndex++)
            {
                string GroupNewsItemId = (string)dtResult.Rows[iIndex]["GroupNewsItemId"];
                string Subject = (string)dtResult.Rows[iIndex]["Subject"];
                string GroupNewsItemAlias = (string)dtResult.Rows[iIndex]["GroupNewsItemAlias"];
                if (String.IsNullOrEmpty(GroupNewsItemAlias))
                {
                    GroupNewsItemAlias = Environments.ConvertToLatinText(Subject);
                }
                RssChanelCls oRssChanelCls = new RssChanelCls(GroupNewsItemId, Subject, "", "", "");
                oRssChanelCls.ChanelUrl = Environments.HttpWorkingRoot + "/Rss/" + GroupNewsItemAlias + "." + Ext;
                oRssChanelCls.ChanelSavePath = Environments.WorkingPath + "\\Rss";
                oRssChanelCls.ChanelSaveFile = Environments.WorkingPath + "\\Rss\\" + GroupNewsItemAlias + "." + Ext;

                rssChannels[iIndex] = oRssChanelCls;
            }
            return rssChannels;
        }

        public static DataTable ReadingForRss(string GroupNewsItemId, int TOP, string belongSite)
        {
            string Query = "select TOP " + TOP + " NewsId,ShortId, belongSite,ImageUrl,Subject=[" + belongSite + "Subject],EntryDate,ShortContent=[" + belongSite + "ShortContent] from TableNews where fk_GroupNewsItem_Id='" + GroupNewsItemId + "'" +
                           "    order by ShowOnTop DESC, EntryDate DESC";
            SqlConnection sqlConnection = new SqlConnection(Environment.Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = Query;
            DataTable dtResult = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
            da.Fill(dtResult);
            return dtResult;
        }

        public RssChanelInfo MakeXmlDataForChanel(
            string Title,
            string Description,
            string Link,
            string CopyRight,
            string Generator,
            DateTime PubDate,
            DateTime LastBuildDate,
            string ChanelId,
            string Ext,
            string belongSite)
        {

            if (Ext == null) Ext = "rss";
            RssChanelCls[] rssChannels = GetRssChannel(Ext, belongSite);
            for (int iIndex = 0; iIndex < rssChannels.Length; iIndex++)
            {
                if (rssChannels[iIndex].ChanelId.Equals(ChanelId))
                {
                    RssChanelCls FoundRssChanel = rssChannels[iIndex];
                    string XmlSaveFile = FoundRssChanel.ChanelSaveFile;
                    DataTable dtGroupNewsItem = ReadingForRss(FoundRssChanel.ChanelId, 30, belongSite);
                    Collection<RssItemCls> RssItems = new Collection<RssItemCls> { };
                    for (int iIndexNews = 0; iIndexNews < dtGroupNewsItem.Rows.Count; iIndexNews++)
                    {
                        //string belongSite1 = (string)dtGroupNewsItem.Rows[iIndexNews]["belongSite"];
                        string _ItemTitle = (string)dtGroupNewsItem.Rows[iIndexNews]["Subject"];
                        string _ItemDescription = (string)dtGroupNewsItem.Rows[iIndexNews]["ShortContent"];
                        string ShortId = (string)dtGroupNewsItem.Rows[iIndexNews]["ShortId"];
                        string _ItemLink = Environments.GetNewsUrl(belongSite, ShortId, _ItemTitle, "_runtime");
                        string _ImageUrl = (string)dtGroupNewsItem.Rows[iIndexNews]["ImageUrl"];
                        DateTime _ItemPubDate = (DateTime)dtGroupNewsItem.Rows[iIndexNews]["EntryDate"];

                        // Check Image exist or not
                        _ImageUrl = (!string.IsNullOrEmpty(_ImageUrl))
                            ? "<img width = \"130px\" hight = \"100px\" src=\"" + Environments.HttpMediaRoot + "/media/" +
                            Environments.PortalAlias + "/news/images/" +
                            belongSite + "/" + _ImageUrl + "\" alt=thumbnail>"
                            : string.Empty;

                        RssItems.Add(new RssItemCls(_ItemTitle, _ItemDescription, _ItemLink, _ItemPubDate, _ImageUrl));
                    }
                    string Xml = GetRssXmlData(Title, Description, Link, CopyRight, Generator, PubDate, LastBuildDate, RssItems);
                    RssChanelInfo RssChanelInfo = new RssChanelInfo();
                    RssChanelInfo.SavedFile = FoundRssChanel.ChanelSaveFile;
                    RssChanelInfo.Url = FoundRssChanel.ChanelUrl;

                    FileStream fs = new FileStream(RssChanelInfo.SavedFile, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.Write(Xml);
                    sw.Close();
                    return RssChanelInfo;
                }
            }

            throw new Exception("Không tìm thấy kênh thông tin Rss!");

            //
        }

        public static string GetRssXmlData(
            string Title,
            string Description,
            string Link,
            string CopyRight,
            string Generator,
            DateTime PubDate,
            DateTime LastBuildDate,
            Collection<RssItemCls> RssItems)
        {
            if (RssItems == null) RssItems = new Collection<RssItemCls> { };
            string XmlData =
              "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
              "<rss version=\"2.0\">\r\n" +
              "<channel>\r\n" +
              "  <title>" + Title + "</title>\r\n" +
              "  <description>" + Description + "</description>\r\n" +
              "  <link>" + Link + "</link>\r\n" +
              "  <copyright>" + CopyRight + "</copyright>\r\n" +
              "  <generator>" + Generator + "</generator>\r\n" +
              "  <pubDate>" + PubDate.ToString() + " GMT" + "</pubDate>\r\n" +
              "  <lastBuildDate>" + LastBuildDate.ToString() + " GMT" + "</lastBuildDate>\r\n";
            for (int iIndex = 0; iIndex < RssItems.Count; iIndex++)
            {
                XmlData +=
                    "<item>\r\n" +
                    "    <title><![CDATA[ " + RssItems[iIndex].ItemTitle + " ]]></title>\r\n" +
                    "    <description><![CDATA[ <a  href=\"" + RssItems[iIndex].Itemlink + "\">" + RssItems[iIndex].Image + "</a>" +
                            RssItems[iIndex].ItemDescription + " ]]></description>\r\n" +
                    "    <link>" + RssItems[iIndex].Itemlink + "</link>\r\n" +
                    "    <pubDate>" + RssItems[iIndex].ItemPubDate.ToString() + " GMT</pubDate>\r\n" +
                    "</item>\r\n";
            }
            XmlData +=
                "  </channel>\r\n" +
                "</rss>\r\n";
            return XmlData;
        }
    }
}
